<template>
  <div class="video-comp">
    <iframe
      v-if="hasIframe"
      width="100%"
      :src="options.url"
      :id="videoId"
      allowfullscreen
    >
    </iframe>
    <div v-else class="video-comp-container" :id="videoId"></div>
    <div v-if="hasShowPic" class="pic-container" style="height: calc(100% - 96px); top: 48px;">
      <img v-if="capturePicture" class="pic" :src="capturePicture" />
      <i class="iconfont iconplay" @click="handlePlay"></i>
    </div>
  </div>
</template>

<script>
import EZUIKit from 'ezuikit-js';

export default {
  props: {
    // 播放配置参数
    data: {
      type: Object,
      default: () => ({})
    },
    // 是否直接采用iframe播放
    hasIframe: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      timer: null,
      hideTimer: null,
      // 播放实例
      player: null,
      // 播放配置参数
      options: {},
      // 视频容器id
      videoId: `video${this.$getRandomNum()}`,
      // 当前直播截图信息
      picOptions: {},
      // 是否展示截图
      hasShowPic: false,
    };
  },
  computed: {
    capturePicture() {
      return this.picOptions[this.videoId];
    }
  },
  watch: {
    // 监听直播配置参数
    data: {
      deep: true,
      handler: function (val, oldVal) {
        const hasObj = (param) => this.$checkType(param) === 'object';
        if (hasObj(val) && hasObj(oldVal)) {
          const hasChange = Object.keys(val).every(key => {
            return oldVal[key] === val[key];
          });
          const dom = document.getElementById(this.videoId);
          if (!hasChange && dom) {
            this.stop();
            // dom.style.opacity = 0;
            const children = dom.children;
            for (let i = 0; i < children.length; i++) {
              dom.removeChild(children[i]);
            }
            this.init();
            // this.hideTimer && clearTimeout(this.hideTimer);
            // this.hideTimer = setTimeout(() => {
            //   dom.style.opacity = 1;
            // }, 100);
          }
        }
      }
    }
  },
  mounted() {
    this.init();
    window.addEventListener('message', this.messageFn);
  },
  beforeDestroy() {
    window.removeEventListener('message', this.messageFn);
    this.timer && clearTimeout(this.timer);
    this.hideTimer && clearTimeout(this.hideTimer);
    this.stop();
  },
  methods: {
    /**
     * 设置video配置
     * id: 视频容器ID
     * url: 直播地址
     * accessToken: 直播鉴权token
     * template： simple - 极简版;standard-标准版;security - 安防版(预览回放);voice-语音版；
     * header：视频上方头部控件, 如果templete参数不为simple,该字段将被覆盖
     * footer： 视频下方底部控件， 如果template参数不为simple,该字段将被覆盖
     */
    init() {
      const config = this.$checkType(this.data) === 'object' ? this.data : {};
      this.options = {
        id: this.videoId,
        accessToken: '',
        url: '',
        autoplay: true,
        template: 'security',
        handleSuccess: this.handleSuccess,
        // header: ['capturePicture', 'save', 'zoom'],
        // footer: ['hd', 'fullScreen']
        ...config
      };
      Object.keys(config).length && this.play();
    },
    // 直播初始化
    play() {
      if (this.hasIframe) return;
      this.player = new EZUIKit.EZUIKitPlayer(this.options);
      if (!this.options.autoplay) {
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(this.pause, 8000);
      }
    },
    iframePlay() {
      /* iframe 支持方法 */
      // this.player.postMessage("play", "https://open.ys7.com/ezopen/h5/iframe"); /* 播放 */
      // this.player.postMessage("capturePicture", "https://open.ys7.com/ezopen/h5/iframe"); /* 截图 */
      // this.player.postMessage("openSound", "https://open.ys7.com/ezopen/h5/iframe"); /* 开启声音 */
      // this.player.postMessage("closeSound", "https://open.ys7.com/ezopen/h5/iframe"); /* 关闭声音 */
      // this.player.postMessage("startSave", "https://open.ys7.com/ezopen/h5/iframe"); /* 开始录制 */
      // this.player.postMessage("stopSave", "https://open.ys7.com/ezopen/h5/iframe"); /* 结束录制 */
    },
    // 监听postMessage的回调
    messageFn(e) {
      if (!e) return;
      try {
        const { data } = e;
        if (data && data.type === 'capturePicture') {
          const u8arr = data.data && data.data.fileUint8Array;
          if (u8arr) {
            // 将截图文件数据转成base64
            const imgBase64 = this.$arrayBufferToBase64(u8arr);
            if (!this.picOptions.hasOwnProperty(this.videoId)) {
              this.picOptions = {
                ...this.picOptions,
                [data.id]: `data:image/png;base64, ${imgBase64}`
              };
            }
          }
        }
      } catch (e) {}
    },
    // 播放当前直播
    handlePlay() {
      this.player && this.player.play();
      this.hasShowPic = false;
    },
    handleSuccess(res) {
      this.options.audio === 0 && this.player.closeSound();
    },
    /**
     * 结束播放
     * @param hasCapture {Boolean} 是否截图
     */
    pause(hasCapture = true) {
      if (!this.player) return;
      if (this.hasIframe) {
        this.player.postMessage('stop', this.options.url);
      } else {
        // 关闭直播时获取截图
        hasCapture && this.player.capturePicture(this.videoId, true);
        this.player.stop();
        if (!this.options.autoplay) this.hasShowPic = true;
      }
    },
    // 清除播放
    stop() {
      this.pause(false);
      this.player = null;
      this.timer && clearTimeout(this.timer);
      this.hideTimer && clearTimeout(this.hideTimer);
    }
  }
};
</script>

<style scoped lang="scss">
.video-comp {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  .video-comp-container {
    width: 100%;
    height: 100%;
    transition: all 50ms;
  }
  .pic-container {
    position: absolute;
    width: 100%;
    height: 65%;
    display: block;
    z-index: 10;
    .pic {
      width: 100%;
      height: 100%;
    }
    i {
      position: absolute;
      width: 40px;
      height: 40px;
      font-size: 40px;
      top: calc(50% - 20px);
      left: calc(50% - 20px);
      display: block;
      text-align: center;
      line-height: 50px;
      cursor: pointer;
    }
  }
}
</style>
